<?php
namespace Vioscope;

if ( ! class_exists( '\Vioscope\Search' ) ) :

require_once( __DIR__ . '/common.php' );

class Search {
	public $search_query;
	public $page;
	public $total_page; // TODO: implement

	function __construct( $search_query = null, $page = 1, $search_params = null, $region = null ) {
		if ( $search_query ) {
			$this->run_search( $search_query, $page, $search_params, $region );
		}
	}

	public function run_search( $search_query = null, $page = 1, $search_params = null, $region = null ) {
		if ( ! $search_query ) {
			$search_query = $this->search_query;
		}
		if ( trim( $search_query ) == '' ) {
			return false;
		}
		$this->search_query = trim( $search_query );
		$this->page = $page;
		// Get result data
		$search_query = urlencode( $search_query );
		if ( ! $search_params ) {
			$search_params = $this->produce_search_params();
		}
		// TODO: Implement more parameters
		$body = get_url_contents( "https://www.youtube.com/results?q=$search_query&page=$page&hl=en" );
		$initial_data = get_initial_data( $body );
		return extract_items( $initial_data );
	}
	
	
	/**
	 * Returns search params for a search to be performed.
	 *
	 * @param str $sort Sort order.
	 * @param str $date Date to be searched for.
	 * @param str $content_type Content type to search for.
	 * @param str $duration Content of duration to search for.
	 * @param str $features Features to search for.
	 * @return str
	 */
	// TODO: Translate over from https://github.com/iv-org/invidious/blob/452d1e8307d6344dd51c5437ccd032a566291c34/src/invidious/search.cr#L266
	public function produce_search_params( $sort = 'relevance', $date = '', $content_type = '',
						  $duration = '', $features = array() ) {
		switch ($sort) {
			case "relevance":
				// do something
				break;
			case "rating":
				// do something
				break;
			case "upload_date":
				// do something
				break;
			case "view_count":
				// do something
				break;
			default:
				// do something
		}
		return ''; // TODO: Return actual stuff
	}
	
	/**
	 * Gives the search page url for next, previous or based on defined page
	 * number.
	 *
	 * @param bool|int $next For next page set it to true, false for previous
	 *    and any integer for specific page.
	 * @return bool|str Either page url or false.
	 */
	// TODO: Create get_next_page_url and get_previous_page_url functions 
	// utilizing this one.
	public function get_change_page_url( $next = true ) {
		$page = $this->page;
		if ( ! is_numeric( $next ) ) {
			if ( $next == true ) {
				$page++;
			} else {
				$page--;
			}
		} else {
			$page = $next;
		}
		if ( $page < 1 ) { // TODO: Add $this->total_page in logic
			return false;
		}
		return get_base_url() . '/search?q=' . $this->search_query . '&page=' . $page;
	}

}

endif;
